<template>
	<view class="createAiPersonStepOne bg-white">
		<view class="flex justify-start align-center">
			<view class="createAiPersonStepOne-imgBox">
				<view v-if="!imgLoading" @click="imgPreviewClick"
					class="createAiPersonStepOne-imgBox-preview flex justify-center align-center">
					<u--image v-if="currentImg" :src="currentImg" mode="aspectFit" width="80vw"
						height="80vw"></u--image>
					<view v-else class="flex align-center justify-center" style="flex-direction: column;">
						<u-icon size="38" name="camera" color="#909399"></u-icon>
						<u-text text='点击拍照' color="#909399"></u-text>
					</view>
				</view>
				<view v-else class="createAiPersonStepOne-imgBox-preview flex justify-center align-center">
					<u-loading-icon size="36" text="AI正在生成您的数字人形象, \n该过程需要10~20秒,请耐心等待..." vertical></u-loading-icon>
				</view>
				<view v-if="currentImg" class="flex align-start justify-start">
					<view class="mt-10">
						<u-button @click="imgPreviewClick" icon="camera" text="重拍"></u-button>
					</view>
				</view>
			</view>
		</view>

		<view class="createAiPersonStepOne-uploadTips flex align-start">
			<view class="mr-10">
				<u-icon size="18" name="info-circle" color="#909399"></u-icon>
			</view>
			<view style="display: inline-block;">
				<text style="color:#909399; font-size: 30rpx;">请在光线合适的位置拍摄自己的半身像,神态自然，不露齿。</text>
				<text @click="previewSampleLinkClick"
					style="display: inline-block; text-decoration: underline;color:#2979ff">示例</text>
			</view>

		</view>
		<view class="createAiPersonStepOne-uploadTips flex align-start">
			<view class="mr-10">
				<u-icon size="18" name="info-circle" color="#909399"></u-icon>
			</view>
			<u-text text='系统会自动对照片进行适度美颜和裁剪'
				color="#909399"></u-text>
		</view>
		<view class="createAiPersonStepOne-btnList flex justify-between">
				<u-button @click="nextStepBtnClick" text="下一步" shape="circle" type="primary" size="large"></u-button>

		</view>
		<u-toast ref="toast"></u-toast>
	</view>
</template>

<script>
	import api from "@/api/api";
	export default {
		data() {
			return {
				currentImg: "",
				uploadImg: "",
				imgLoading: false,
				createAiImageTask: {},
				cropFaceTaskId: null
			};
		},
		components: {},
		props: {},
		computed: {},
		onReady() {},
		async onLoad(option) {
			this.currentImg = option && option.imgUrl ? option.imgUrl : null;
			this.cropFaceTaskId = option && option.cropFaceTaskId ? option.cropFaceTaskId : null;
		},
		mounted() {},
		onShow() {},
		methods: {
			async imgPreviewClick() {
				try {
					const hasPermission = await this.checkCameraPermission();
					if (hasPermission) {
						// 有权限，可以调用相机
						let vue = this;
						uni.chooseImage({
							sourceType: ['camera'],
							sizeType: ['original'],
							crop: {
								width: 512,
								height: 512
							},
							success: async function(res) {
								console.log("resImg", img)
								let img = res.tempFilePaths[0];
								console.log("img", img)
								let res2 = await vue.depot.uploadFile(
										api.document("document/uploadDocument"), img)
									.catch(err => {});
								if (res2 && res2.data && res2.data.accessUrl) {
									vue.currentImg = res2.data.accessUrl;
									let res3 = await vue.depot.get(api.aiCard("replicateTask/cropFace?imgUrl=" + res2.data.accessUrl))
									vue.cropFaceTaskId = res3 && res3.data && res3.data.data ? res3.data.data : null;
								}
							},
							fail:function(error){
							}
						});
					} else {
						uni.showToast({
							title: '未授权相机权限',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('权限检查出错:', error);
				}
				
			},
			previewSampleLinkClick() {
				uni.previewImage({
					urls: ["https://sadtalker.oss-cn-hangzhou.aliyuncs.com/sales2.png"]
				});
			},
			async aiGenPicBtnClick() {
				try {
					if (!this.currentImg) {
						this.$refs.toast.show({
							type: "error",
							title: "提示",
							message: "请先上传您的半身照"
						});
						return;
					}
					this.imgLoading = true;
					this.createAiImageTask = {};
					let createImgRes = await this.depot.post(api.aiCard("wechatUserImage/createAiImage"), {
						srcImgUrl: this.uploadImg
					})
					if (createImgRes && createImgRes.data && createImgRes.data.data) {
						let createImageTaskId = createImgRes.data.data;
						let tryCount = 30;
						for (let tryTime = 0; tryTime < tryCount; tryTime++) {
							await new Promise((resolve) => {
								setTimeout(() => {
									resolve()
								}, 1000)
							})
							let findTaskStatusRes = await this.depot.get(api.aiCard(
								"wechatUserImage/findCreateAiImageTaskProcess?createAiImageLogId=" +
								createImageTaskId))
							if (findTaskStatusRes && findTaskStatusRes.data && findTaskStatusRes.data.data) {
								let createImageTask = findTaskStatusRes.data.data;
								if (createImageTask.createStatus === "DONE") {
									this.currentImg = createImageTask.aiImgUrl;
									this.imgLoading = false;
									break;
								}
								if (createImageTask.status === "FAIL") {
									this.imgLoading = false;
									this.$refs.toast.show({
										type: "error",
										title: "提示",
										message: "AI生成数字人形象失败， 请稍后再试!"
									});
								}
							}
							if (tryTime == tryCount - 1) {
								this.$refs.toast.show({
									type: "error",
									title: "提示",
									message: "AI生成数字人形象超时， 请稍后再试!"
								});
								this.imgLoading = false;
							}
						}
						// let findTaskStatusInterval = setInterval(async () => {
						// 	if (vue.createAiImageTask && vue.createAiImageTask.createStatus == "DONE") {
						// 		return;
						// 	}
						// 	let findTaskStatusRes = await this.depot.get(api.aiCard("wechatUserImage/findCreateAiImageTaskProcess?createAiImageLogId=" + createImageTaskId))
						// 	.catch(() => {
						// 		clearInterval(findTaskStatusInterval)
						// 	})
						// 	if (findTaskStatusRes && findTaskStatusRes.data && findTaskStatusRes.data.data) {
						// 		vue.createImageTask = findTaskStatusRes.data.data;
						// 		if (vue.createImageTask.createStatus === "DONE") {
						// 			vue.currentImg = vue.createImageTask.aiImgUrl;
						// 			vue.imgLoading = false;
						// 			clearInterval(findTaskStatusInterval)
						// 		}
						// 		if (vue.createImageTask.status === "FAIL") {
						// 			vue.imgLoading = false;
						// 			clearInterval(findTaskStatusInterval)
						// 			this.$refs.toast.show({
						// 				type: "error",
						// 				title: "提示",
						// 				message: "AI生成数字人形象失败， 请稍后再试!"
						// 			});
						// 		}
						// 	}
						// }, 1000, createImageTaskId)

						// 30秒后关闭，防止内存溢出
						// setTimeout(() => {
						// 	if (findTaskStatusInterval) {
						// 		clearInterval(findTaskStatusInterval)
						// 		vue.imgLoading = false;
						// 	}
						// }, 60000)
					} else {
						throw new Error("调用合成音频接口失败");
					}
				} catch (e) {
					this.$refs.toast.show({
						type: "error",
						title: "提示",
						message: "AI生成数字人形象失败， 请稍后再试!"
					});
				}

			},
			nextStepBtnClick() {
				if (this.currentImg) {
					uni.navigateTo({
						url: "/pages/aiPerson/createAiPersonStepTwo?imgUrl=" + this.currentImg + "&cropFaceTaskId=" + this.cropFaceTaskId
					})
				} else {
					this.$refs.toast.show({
						type: "error",
						title: "提示",
						message: "请先上传您的半身照"
					});
				}
			},
			checkCameraPermission() {
				return new Promise((resolve, reject) => {
					// 1. 首先检查当前权限设置
					uni.getSetting({
						success(res) {
							// 检查是否已授权相机权限
							if (res.authSetting['scope.camera']) {
								// 已授权
								resolve(true);
							} else {
								// 2. 未授权，尝试请求权限
								uni.authorize({
									scope: 'scope.camera',
									success() {
										// 用户同意授权
										resolve(true);
									},
									fail(err) {
										// 用户拒绝授权
										console.log('授权失败:', err);

										// 3. 引导用户去设置页手动开启权限
										uni.showModal({
											title: '提示',
											content: '需要相机权限才能使用拍照功能，是否去设置开启权限？',
											confirmText: '去设置',
											cancelText: '取消',
											success: (modalRes) => {
												if (modalRes.confirm) {
													// 打开设置页
													uni.openSetting({
														success(settingRes) {
															if (settingRes
																.authSetting[
																	'scope.camera'
																	]) {
																// 用户在设置页开启了权限
																resolve(true);
															} else {
																// 用户在设置页仍然拒绝授权
																resolve(false);
															}
														},
														fail() {
															reject('打开设置页失败');
														}
													});
												} else {
													// 用户点击取消
													resolve(false);
												}
											}
										});
									}
								});
							}
						},
						fail(err) {
							reject('获取设置失败: ' + err.errMsg);
						}
					});
				});
			}
		}
	};
</script>

<style lang="less" scoped>
	.createAiPersonStepOne {
		height: 100vh;

		&-imgBox {
			margin-left: 10vw;

			&-preview {
				margin-top: 40rpx;
				height: 80vw;
				width: 80vw;
				border: 1rpx solid #e4e7ed;
			}
		}

		&-uploadTips {
			width: 80vw;
			margin-top: 20rpx;
			margin-left: 10vw;
			color: #909399;
		}

		&-btnList {
			width: 100vw;
			padding-left: 2vw;
			padding-right: 2vw;
			position: fixed;
			bottom: env(safe-area-inset-bottom);

			&-btn {
				width: 47vw;
			}
		}
	}
</style>